// pages/user/settings/bind-phone/bind-phone.js
const api = require('../../../../utils/api/index');

Page({
  data: {
    phone: '',
    verifyCode: '',
    isLoading: false,
    countDown: 0,
    isCounting: false
  },

  inputPhone(e) {
    this.setData({ phone: e.detail.value });
  },

  inputVerifyCode(e) {
    this.setData({ verifyCode: e.detail.value });
  },

  getVerifyCode() {
    const { phone, isCounting } = this.data;
    if (isCounting) return;

    if (!phone || phone.length !== 11) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
      return;
    }

    wx.showLoading({ title: '发送中...' });
    api.auth.sendSmsCode({ phone, purpose: 'bind' }, { loading: false })
      .then(() => {
        wx.hideLoading();
        wx.showToast({ title: '验证码已发送', icon: 'success' });
        this.setData({ countDown: 60, isCounting: true });
        this.startCountDown();
      })
      .catch(err => {
        wx.hideLoading();
        wx.showToast({ title: err.message || '发送失败', icon: 'none' });
      });
  },

  startCountDown() {
    const timer = setInterval(() => {
      const next = this.data.countDown - 1;
      if (next <= 0) {
        clearInterval(timer);
        this.setData({ countDown: 0, isCounting: false });
      } else {
        this.setData({ countDown: next });
      }
    }, 1000);
  },

  submitForm() {
    const { phone, verifyCode } = this.data;

    if (!phone || phone.length !== 11) {
      wx.showToast({ title: '请输入正确的手机号', icon: 'none' });
      return;
    }
    if (!verifyCode || verifyCode.length !== 6) {
      wx.showToast({ title: '请输入正确的验证码', icon: 'none' });
      return;
    }

    this.setData({ isLoading: true });

    api.user.bindPhone({ phone, code: verifyCode })
      .then(() => {
        this.setData({ isLoading: false });
        wx.setStorageSync('phone', phone);
        wx.showToast({ title: '绑定成功', icon: 'success' });
        wx.navigateBack();
      })
      .catch(err => {
        this.setData({ isLoading: false });
        wx.showToast({ title: err.message || '绑定失败', icon: 'none' });
      });
  }
});